import axios from 'axios'
import qs from 'qs'
import store from '../store'
import { getDomain } from '@/libs/tools'
import xeUtils from 'xe-utils'
// import { Toast } from 'vant'

const addErrorLog = errorInfo => {
  // TODO 对错误日志进行收集
}

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }

  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/json; charset=utf-8'
      }
    }
    return config
  }

  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // TODO页面取消正在加载的特效
    }
  }

  interceptors (instance, options) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // Toast.loading({
      //   message: '加载中...',
      //   forbidClick: true,
      //   duration: 10000
      // })
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // TODO根据不同框架添加不同的加载特效
      }
      this.queue[options.url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      let routeName = localStorage.getItem('type')
      console.log(`https://shengstapi.tripln.top/api/uc/ctcyq/oauth2Service/authorize?appid=${xeUtils.locat().host === 'record.lngov.top' ? 'sst8h96jcys2zerhouc' : 'sstt59oh9eijq5prq9f'}&redirect_uri=http%3A%2F%2F${xeUtils.locat().host === 'record.lngov.top' ? 'record.lngov.top' : 'truckdriverrecord.tripln.top'}%2Frailway%2F%23%2F${routeName || 'home'}&response_type=code#shengst_redirect`)
      // Toast.clear()
      this.destroy(options.url)
      const { data, status } = res
      // Toast.clear()
      console.log(res, '#$@$@#$@#$@#$')
      if (data.errcode === 1001 || (data.errmsg && data.errmsg.indexOf('token') != -1)) {
        let routeName = localStorage.getItem('type')
        if (routeName === 'none') return
        window.location.href = `https://shengstapi.tripln.top/api/uc/ctcyq/oauth2Service/authorize?appid=${xeUtils.locat().host === 'record.lngov.top' ? 'sst8h96jcys2zerhouc' : 'sstt59oh9eijq5prq9f'}&redirect_uri=http%3A%2F%2F${xeUtils.locat().host === 'record.lngov.top' ? 'record.lngov.top' : 'truckdriverrecord.tripln.top'}%2Frailway%2F%23%2F${routeName || 'home'}&response_type=code#shengst_redirect`
        // alert(1)
        // console.log('EEEEEEEE')
        // let self_url = encodeURIComponent(window.location.href.replace(/#/g, '$'))
        // console.log(self_url, 'self_url'
        // // ' + (options.goApi ? options.goApi : 'api') +
        // location.href = this.baseUrl + '/api/uc/qmc/hsMobileService/getUrlForNologin?testip=false&returnUrl=' + self_url
        // // // console.log(this.baseUrl + '/api/uc/csc/qstbMobileService/getUrlForNologin?testip=false&returnUrl=' + self_url)
      }
      return { data, status }
    }, error => {
      // Toast.clear()
      this.destroy(options.url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
      }
      addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }

  request (options) {
    const instance = axios.create()
    if (options.type === 'get') {
      options.method = 'get'
      options.params = options.data
    } else {
      options.method = 'post'
    }

    if (getDomain(options.url)) {
      let url = getDomain(options.url)
      if (store.state.app.juyouTicket[url]) {
        options.headers = { 'juyou-ticket': store.state.app.juyouTicket[url] }
      }
    }
    delete options.type
    if (options.php === true) {
      if (options.headers) {
        options.headers = Object.assign(options.headers, { 'Content-Type': 'application/x-www-form-urlencoded' })
      } else {
        options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
      }
      options.data = qs.stringify(options.data)
    }
    options.withCredentials = true

    options = Object.assign(this.getInsideConfig(), options)

    this.interceptors(instance, options)
    if (options.await === true) {
      return new Promise((resolve, reject) => {
        instance(options)
          .then((response) => {
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    } else {
      return instance(options)
    }
  }
}

export default HttpRequest
